package com.dxp.controller;

import com.dxp.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //获取文件名称
        String filename = file.getOriginalFilename();
        //文件保存位置
        String suffix=filename.substring(filename.lastIndexOf("."));
        String fileName=UUID.randomUUID().toString().replaceAll("-", "")+suffix;

        //如果不存在,创建一个
        File realPath = new File(basePath);
        if(!realPath.exists())
        {
            realPath.mkdirs();
        }
        file.transferTo(new File(basePath+fileName));
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(name, "UTF-8"));
        //输入流
        FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //缓冲区
        byte[] buffer = new byte[1024];
        int len=0;
        while((len=fileInputStream.read(buffer))!=-1)
        {
            outputStream.write(buffer, 0, len);
            outputStream.flush();
        }
        fileInputStream.close();
        outputStream.close();


    }
}
